#include "StatusBar.h"
#include "MainFrame.h"
#if WIN32
#include <qt_windows.h>
#endif
#include <widgets/SImageButton.h>
#include <QBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QDateTime>
#include <QSlider> 
#include <QLibrary>
#include <QDebug>
#include <QAction>
#include <QPushButton>
#include <QIcon>
#include <QMenuBar>
#include <QPainterPath>
#include <QMouseEvent>
#include "core/StyleMgr.h"


DisconnectShow::DisconnectShow(QWidget* parent/* = nullptr*/)
	: QWidget(parent),
	  m_netStatus(0),
	  m_connecting(false),
	  m_networkStatus(nullptr),
	  m_customer(nullptr),
	  m_tryButton(nullptr)
{
	InitUI();
}

DisconnectShow::~DisconnectShow()
{
}

void DisconnectShow::InitUI(void)
{
	//设置窗口大小
	setFixedSize(225, 62);
	//设置无标题栏 toolwindow
	setWindowFlags(Qt::FramelessWindowHint|Qt::Tool/*|Qt::WindowStaysOnTopHint*/);
	//设置窗口透明
	setAttribute(Qt::WA_TranslucentBackground);

	// 窗口布局
	// /￣￣￣￣￣￣￣|￣￣￣￣|￣￣￣￣￣￣\
	// |			 | QLabel| pushbutton |
	// |SImageButton |_______|____________|
	// |			 | QLabel		      |
	// \_____________|____________________/
	//    \/
	QFont ft;
	ft.setPointSize(10);
	ft.setBold(true);
	QPalette pe;
	pe.setColor(QPalette::WindowText, Qt::black);

	m_networkStatus = new QLabel("服务器连接失败！");
	m_networkStatus->setPalette(pe);
	m_networkStatus->setFont(ft);
	m_networkStatus->setAlignment(Qt::AlignLeft|Qt::AlignBottom);

	m_customer = new QLabel("联系客服：400-609-1322");
	m_customer->setPalette(pe);
	m_customer->setFont(ft);
	m_customer->setAlignment(Qt::AlignLeft|Qt::AlignTop);

	m_tryButton = new QPushButton("重试");
	m_tryButton->setFixedSize(50, 23);
	m_tryButton->setStyleSheet("QPushButton{color:black; border:0px; background-color:rgb(76,172,160);}");
	connect(m_tryButton, &QPushButton::clicked, this, &DisconnectShow::OnTryAgainClicked);

	QHBoxLayout* mainLayout = new QHBoxLayout;
	mainLayout->setSpacing(13);
	mainLayout->addWidget(new SImageButton(this, "guiframe_status_error"));

	QHBoxLayout* rightTopLayout = new QHBoxLayout;
	rightTopLayout->setSpacing(10);
	rightTopLayout->addWidget(m_networkStatus);
	rightTopLayout->addWidget(m_tryButton);

	QVBoxLayout* rightLayout = new QVBoxLayout;
	rightLayout->setSpacing(0);
	rightLayout->addLayout(rightTopLayout);
	rightLayout->addWidget(m_customer);
	mainLayout->addLayout(rightLayout);
	setLayout(mainLayout);
}

void DisconnectShow::OnTryAgainClicked() {
	SetConnectingStatus(true);

	typedef void(*tryAgain)();
	auto fun = (tryAgain)QLibrary::resolve("qeubee", "tryConnectAgain");
	if (fun != nullptr)
	{
		fun();
	}
}

void DisconnectShow::SetConnectingStatus(bool connecting) 
{
	m_connecting = connecting;
	if (m_connecting)
	{
		m_networkStatus->setText("无法连接服务器！");
		m_customer->setText("正在尝试重新连接...");
		m_tryButton->hide();
	}
	else
	{
		m_networkStatus->setText("服务器连接失败！");
		m_customer->setText("联系客服：400-609-1322");
		m_tryButton->show();
	}
	update();
}

void DisconnectShow::paintEvent(QPaintEvent* event) 
{
	QRect R = rect();
	QPainterPath drawPath;
	qreal ARROW_HEIGHT = 5.0;
	qreal OFFSET_X_Y = 6.0;

	//增加圆角矩形
	QRect roundedRect(R.left(), R.top(), R.width(), R.height() - ARROW_HEIGHT - 2);
	drawPath.addRoundedRect(roundedRect, OFFSET_X_Y, OFFSET_X_Y);

	//增加三角形
	QPolygonF trianglePolygon;
	trianglePolygon << QPointF(R.left()+15.5, R.height()-ARROW_HEIGHT-2);
	trianglePolygon << QPointF(R.left()+20.0, R.bottom());
	trianglePolygon << QPointF(R.left()+24.5, R.height()-ARROW_HEIGHT-2);
	drawPath.addPolygon(trianglePolygon);

	//绘制路径
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing, true);
 	painter.setPen(Qt::NoPen);
	painter.setBrush(QColor(255, 234, 183));
	painter.drawPath(drawPath);
}

enum
{
	eFT_PL_SYS_TIME = 6025,
	eFT_PL_FORCE_QUIT = 6028,
	eFT_PL_HEART_BREAK_SYS_OK = 6030,
	eFT_PL_HEART_BREAK_SYS_NOK = 6031,
	eFT_PL_HEART_RECONN_SYS_ING = 6032,
	eFT_PL_HEART_BREAK_SYS_OK2 = 6036,
};

namespace {
	int randInt(int mi, int mx) {
		static int seed = 0x5412437;
		if (mx == mi) {
			return mi;
		}
		if (mi > mx) {
			std::swap(mi, mx);
		}
		QTime tm = QTime::currentTime();
		qsrand(seed + tm.msec() + tm.second() * 1000);
		int last = qrand();
		return mi + (last) % (mx - mi);
	}
}

StatusBar::StatusBar(MainFrame* frame, QWidget* parent/* = nullptr*/)
	: QWidget(parent),
	  m_tmSysTime(nullptr),
	  m_btnNetState(nullptr),
	  m_btnMsgCenter(nullptr),
	  m_dlgDisconnectShow(nullptr),
	  m_tmNetState(nullptr),
	  m_tmAutoHideDlgDisconnect(nullptr),
	  m_msgCount(0),
	  m_netOK(false),
	  m_frame(frame)
{
	initialize();

	//刷新网络状态
	m_tmNetState = new QTimer(this);
	connect(m_tmNetState, &QTimer::timeout, [=]() {
		m_netOK = !m_netOK;
		updateNetStatus();
	});

	//自动隐藏断网提示窗
	m_tmAutoHideDlgDisconnect = new QTimer(this);
	connect(m_tmAutoHideDlgDisconnect, &QTimer::timeout, [=]() {
		if (m_networkState == eFT_PL_HEART_RECONN_SYS_ING
			|| m_networkState == eFT_PL_HEART_BREAK_SYS_OK
			|| m_networkState == eFT_PL_HEART_BREAK_SYS_OK2
			|| m_networkState == eFT_PL_SYS_TIME){
			m_tmAutoHideDlgDisconnect->stop();
			hideDlgDisconnected();
		}
	});
}

StatusBar::~StatusBar()
{
}

void StatusBar::initialize()
{
	setAutoFillBackground(true);
	QPalette palette = this->palette();
	palette.setColor(QPalette::Window, NAME_COLOR("MainTitleBack"));
	setPalette(palette);

	QHBoxLayout* layout = new QHBoxLayout();
	layout->setContentsMargins(10, 0, 10, 0);
	layout->setSpacing(8);
	layout->addStretch();
	
	//系统时间
	QLabel* systime = new QLabel(this);
	systime->setContentsMargins(10, 0, 10, 0);
	layout->addWidget(systime, 0, Qt::AlignVCenter);
	m_tmSysTime = new QTimer(this);
	m_tmSysTime->callOnTimeout(this, [systime, this](){
			QColor color = NAME_COLOR("TxtDisabled");
			QRgb txtRgb = qRgb(color.red(), color.green(), color.blue());
			QString txtRgbStr = QString::number(txtRgb,16);
			static QString title = "<p style=\"font-size:%1px; color:#%2\">%3</p>";
			systime->setText(title.arg(12).arg(txtRgbStr).arg(getSystemTime()));
		});
	m_tmSysTime->setInterval(1000);
	m_tmSysTime->start();

	//网络状态
	m_btnNetState = new SImageButton(this, "guiframe_state_online");
	layout->addWidget(m_btnNetState, 0, Qt::AlignVCenter);

	//帮助中心
	SImageButton* btnHelp = new SImageButton(this, "guiframe_button_help");
	btnHelp->setToolTip("帮助中心");
	btnHelp->setStyleSheet("QToolTip{border:1px solid #308376;font:12px Microsoft YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235, 200)}");
	btnHelp->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	btnHelp->setFixedSize(24, 24);
	layout->addWidget(btnHelp, 0, Qt::AlignVCenter);
	connect(btnHelp, &SImageButton::clicked, this, &StatusBar::onHelpClicked);

	//消息中心
	m_btnMsgCenter = new SImageButton(this, "guiframe_app_sound");
	m_btnMsgCenter->setToolTip("消息中心");
	m_btnMsgCenter->setStyleSheet("QToolTip{border:1px solid #308376;font:12px Microsoft YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235, 200)}");
	m_btnMsgCenter->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	m_btnMsgCenter->setFixedSize(24, 24);
	layout->addWidget(m_btnMsgCenter, 0, Qt::AlignVCenter);
	connect(m_btnMsgCenter, &SImageButton::clicked, this, &StatusBar::onNoticeClicked);

	//服务平台
	SImageButton* btnService = new SImageButton(this, "guiframe_app_manager");
	btnService->setToolTip("服务平台");
	btnService->setStyleSheet("QToolTip{border:1px solid #308376;font:12px Microsoft YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235, 200)}");
	btnService->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	btnService->setFixedSize(24, 24);
	layout->addWidget(btnService, 0, Qt::AlignVCenter);

	//账号信息
	static QColor accountBkg[12] = { 0xbf3532, 0xc6532d, 0xc97e33 , 0xcd9838 ,0xd3bd42 ,0x96b93c,
								 0x67a738, 0x51a6a7, 0x3e7dd5 , 0x324cc4 ,0x5c32ae,0xb93c81};
	QColor bk = accountBkg[randInt(0, 11)];
	SImageButton* btnAccountInfo = new SImageButton(this, "guiframe_app_manager");
	btnAccountInfo->setToolTip("账号信息");
	btnAccountInfo->setStyleSheet("QToolTip{border:1px solid #308376;font:12px Microsoft YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235, 200)}");
	btnAccountInfo->setColor(bk, bk, bk, bk);
	btnAccountInfo->setFixedSize(24, 24);
	layout->addWidget(btnAccountInfo, 0, Qt::AlignVCenter);
	connect(btnAccountInfo, &SImageButton::clicked, this, &StatusBar::onAccoutinfoClicked);

	//设置
	SImageButton* btnSetting = new SImageButton(this, "guiframe_dropdown_down");
	btnSetting->setToolTip("设置");
	btnSetting->setStyleSheet("QToolTip{border:1px solid #308376;font:12px Microsoft YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235, 200)}");
	btnSetting->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	btnSetting->setFixedSize(24, 24);
	layout->addWidget(btnSetting, 0, Qt::AlignVCenter);
	connect(btnSetting, &SImageButton::clicked, this, &StatusBar::onSettingClicked);
	setLayout(layout);

	setMouseTracking(true);
}

QString StatusBar::getSystemTime()
{
	typedef time_t (*getSystemTime)(void);
	auto fun = (getSystemTime)QLibrary::resolve("qeubee", "getServerTime");
	if (fun != nullptr) {
		time_t t = fun();
		return QDateTime::fromTime_t(t).toString("ddd hh:mm:ss");
	}
	else {
		return QDateTime::currentDateTime().toString("ddd hh:mm:ss");
	}
}

void StatusBar::onHelpClicked()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr) {
		fun(ClickType::CLICK_HELP);
	}
}

void StatusBar::onNoticeClicked()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr) {
		fun(ClickType::CLICK_NOTICE);
	}

	if (m_msgCount > 0) {
		m_msgCount -= 1;
		update();
	}
}

void StatusBar::onAccoutinfoClicked()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr) {
		fun(ClickType::CLICK_ACCOUNTINFO);
	}
}

void StatusBar::onSettingClicked()
{
	QMenu* menu = new QMenu();
	QAction* aboutQB = new QAction("关于qeubee");
	menu->addAction(aboutQB);
	menu->addSeparator();
	QAction* mobileQB = new QAction("手机qeubee");
	menu->addAction(mobileQB);
	QAction* excelPlugin = new QAction("Excel插件");
	menu->addAction(excelPlugin);
	QAction* sysSetting = new QAction("系统设置");
	menu->addAction(sysSetting);
	QAction* mobileConfirm = new QAction("手机验证");
	menu->addAction(mobileConfirm);
	QAction* logout = new QAction("注销登录");
	menu->addAction(logout);
	menu->setStyleSheet(
		"QMenu{background-color:rgb(32,62,62);color:rgb(255, 235, 200);font:13px Microsoft YaHei;font-weight:bold;}"
		"QMenu::item::selected{background-color:#295d5d;}"
		"QMenu::item{border-bottom:1px solid black;background-color: transparent;padding:4px 20px;margin:0px 0px;}"
		//"QMenu::separator{blackground-color:black;color:black;height:1px;}"
	);
	menu->exec(QCursor::pos());

	connect(aboutQB, &QAction::triggered, this, &StatusBar::onMenuAboutQB);
	connect(mobileQB, &QAction::triggered, this, &StatusBar::onMenuMobileQB);
	connect(excelPlugin, &QAction::triggered, this, &StatusBar::onMenuExcelPlugin);
	connect(sysSetting, &QAction::triggered, this, &StatusBar::onMenuSysSetting);
	connect(mobileConfirm, &QAction::triggered, this, &StatusBar::onMenuMobileConfirm);
	connect(logout, &QAction::triggered, this, &StatusBar::onMenuLogout);
}

void StatusBar::paintEvent(QPaintEvent* event)
{
	QStylePainter painter(this);
	//painter.scale(m_uiScale, m_uiScale);

	//绘制消息中心小红点
	if (m_msgCount > 0)
	{
		QPoint btnPoint = m_btnMsgCenter->pos();
		QSize btnSize = m_btnMsgCenter->size();
		QRect hotRect;
		hotRect.setRect(btnPoint.x()+btnSize.width()-9,btnPoint.y()-2, 7, 7);
		painter.setPen(QColor(219, 31, 29));
		painter.setBrush(QBrush(QColor(219, 31, 29)));
		painter.drawEllipse(hotRect);
	}
}

void StatusBar::resizeEvent(QResizeEvent* event)
{
}

void StatusBar::mouseMoveEvent(QMouseEvent* event)
{
	//this->setCursor(Qt::ArrowCursor);
}

void StatusBar::mousePressEvent(QMouseEvent* event)
{
	QWidget::mousePressEvent(event);
}

void StatusBar::moveEvent(QMoveEvent* event)
{
	onWindowMoved();
}

void StatusBar::onWindowMoved()
{
	if (m_btnNetState != nullptr
		&& m_dlgDisconnectShow != nullptr)
	{
		QPoint pt = m_btnNetState->pos();
		pt = m_btnNetState->mapToGlobal(pt);
		pt.setX(pt.x() - 25);
		pt.setY(pt.y() - 64);
		m_dlgDisconnectShow->move(pt);
	}
}

void StatusBar::setNetworkState(int state)
{
	m_networkState = state;

	//刷新网络状态
	switch (state)
	{
	case eFT_PL_HEART_RECONN_SYS_ING:
		m_netOK = true;
		m_tmNetState->start(500);
		updateNetStatus();
		break;
	case eFT_PL_HEART_BREAK_SYS_OK:
	case eFT_PL_HEART_BREAK_SYS_OK2:
		m_netOK = true;
		m_tmNetState->stop();
		updateNetStatus();
		break;
	case eFT_PL_HEART_BREAK_SYS_NOK:
	case eFT_PL_FORCE_QUIT:
	//case E_FID_QB_KICK_MULTI_TERMINAL:
		m_netOK = false;
		m_tmNetState->stop();
		updateNetStatus();
		break;
	default:
		break;
	}

	//显示/隐藏断网后提示窗口
	if (state==eFT_PL_HEART_RECONN_SYS_ING 
		|| state == eFT_PL_HEART_BREAK_SYS_OK
		|| state == eFT_PL_HEART_BREAK_SYS_OK2
		|| state == eFT_PL_SYS_TIME)
	{
		hideDlgDisconnected();
	}
	else if (state == eFT_PL_HEART_BREAK_SYS_NOK)
	{
		m_tmAutoHideDlgDisconnect->start(60000);
		showDlgDisconnected();
	}
}

void StatusBar::updateNetStatus()
{
	if (m_btnNetState != nullptr)
	{
		m_btnNetState->setImgId(m_netOK ?
			"guiframe_state_online" :
			"guiframe_state_offline");
	}
}

void StatusBar::showDlgDisconnected()
{
	if (m_btnNetState == nullptr)
	{
		return;
	}

	QPoint pt = m_btnNetState->pos();
	pt = m_btnNetState->mapToGlobal(pt);
	pt.setX(pt.x() - 25);
	pt.setY(pt.y() - 64);

	if (m_dlgDisconnectShow == nullptr)
	{
		m_dlgDisconnectShow = new DisconnectShow(this);
	}
	m_dlgDisconnectShow->move(pt);
	m_dlgDisconnectShow->raise();
	if (!m_dlgDisconnectShow->isVisible())
	{
		m_dlgDisconnectShow->show();
	}
	m_dlgDisconnectShow->SetConnectingStatus(false);
}

void StatusBar::hideDlgDisconnected()
{
	if (m_dlgDisconnectShow!=nullptr
		&& m_dlgDisconnectShow->isVisible())
	{
		m_dlgDisconnectShow->hide();
	}
}

void StatusBar::setMsgCenterNotify(int count)
{
	m_msgCount = count;
	update();
}

void StatusBar::onMenuAboutQB()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr)
	{
		fun(ClickType::CLICK_ABOUT);
	}
}

void StatusBar::onMenuMobileQB()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr)
	{
		fun(ClickType::CLICK_QUICKRES);
	}
}

void StatusBar::onMenuExcelPlugin()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr)
	{
		fun(ClickType::CLICK_EXCELADDIN);
	}
}

void StatusBar::onMenuSysSetting()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr)
	{
		fun(ClickType::CLICK_SYSSETTING);
	}
}

void StatusBar::onMenuMobileConfirm()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr)
	{
		fun(ClickType::CLICK_MOBILECONFIRM);
	}
}

void StatusBar::onMenuLogout()
{
	auto fun = (ClickStatusBar)QLibrary::resolve("qeubee", "clickStatusbar");
	if (fun != nullptr)
	{
		fun(ClickType::CLICK_LOGOUT);
	}
}
